<template>
  <div class="specificationbox">
    <!-- 库存 -->
    <el-divider content-position="left">库存</el-divider>
    <el-form
      :model="specificationForm"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="库存">
        <el-input-number
          v-model="addgoodsinfo.goods.stock"
          size="small"
          :disabled="disabledinventory"
          controls-position="right"
        ></el-input-number>
        <strong style="margin-left: 100px">是否显示</strong>
        <el-switch
          class="switchspecification"
          active-text="支持"
          inactive-text="关闭"
          v-model="showspecification"
          @change="showspecificationhandle"
        ></el-switch>
      </el-form-item>

      <el-form-item label="库存状态">
        <el-radio-group
          v-model="specificationstate"
          size="medium"
          @input="specificationstatehanle"
        >
          <el-radio-button label="下单减库存"></el-radio-button>
          <el-radio-button label="付款减库存"></el-radio-button>
          <el-radio-button label="永不减库存"></el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <!-- 规格 -->
    <el-divider content-position="left">规格</el-divider>

    <el-form
      :model="specificationForm"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="启用商品规格">
        <el-switch
          :disabled="enterType === 2"
          class="switchspecification"
          active-text="启用"
          inactive-text="关闭"
          v-model="enablespecifications"
          @change="enablespecificationshandle"
        ></el-switch>
      </el-form-item>
    </el-form>
    <div class="addspecification" v-show="$data._showshowspecification">
      <div class="SpecificationWarning">
        <i class="el-icon-s-opportunity"></i>
        <i>请确保规格及规格项数据为有效数据。</i>
        <i>更改规格及规格项后请点击下方的【刷新规格表】来更新数据。</i>
      </div>

      <div
        class="goods-container"
        v-for="(attr, index) in privateGoodsItem"
        :key="index"
      >
        <div class="goods-content">
          <div class="goods-content-box">
            <div class="goods-content-left">
              <el-form
                label-width="80px"
                style="width: 400px"
                @submit.native.prevent
              >
                <el-form-item label="规格名">
                  <el-input
                    :disabled="enterType === 2"
                    v-model="attr.privateSpecName"
                    placeholder="请输入规格名"
                  ></el-input>
                </el-form-item>
                <el-form-item label="规格值">
                  <el-tag
                    v-for="tag in attr.dynamicTags"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag, attr)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="attr.inputVisible && enterType !== 2"
                    v-model="attr.inputValue"
                    :ref="`saveTagInput${index}`"
                    size="small"
                    @keyup.enter.native="
                      handleInputConfirm(attr.inputValue, attr)
                    "
                    @blur="handleInputConfirm(attr.inputValue, attr)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    :disabled="enterType === 2"
                    class="button-new-tag"
                    size="small"
                    @click="showInput(attr, index)"
                    >+ 添加</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
            <div class="goods-content-right">
              <el-link
                :disabled="enterType === 2"
                type="danger"
                @click="delPrivateSpec(index)"
                >删除规格</el-link
              >
            </div>
          </div>
        </div>
      </div>
      <el-button
        v-if="enterType === 1"
        type="primary"
        :style="{ marginLeft: '5%', marginTop: '20px' }"
        @click="addPrivateSpec"
        >添加规格</el-button
      >
      <el-button type="primary" v-if="enterType === 1" @click="Refresh"
        >刷新规格表
      </el-button>
      <!-- <p style="margin: 24px 0 10px 0">规格表</p> -->
      <el-table
        v-show="showtable"
        ref="multipleTable"
        :data="
          enterType === 1
            ? addgoodsinfo.specItemAttrList
            : tableColumnList.specItemAttrList
        "
        stripe
        tooltip-effect="dark"
        :style="{ width: '90%', marginLop: '1%', marginLeft: '5%' }"
      >
        <!-- 添加商品 显示的 表头 -->
        <div v-if="enterType === 1">
          <el-table-column
            :label="item.specName"
            :property="item.specName"
            v-for="item in addgoodsinfo.goodsSpecList"
            :key="item.specName"
            align="center"
            fixed="left"
          >
            <template slot-scope="scope">
              <span>{{ scope.row[scope.column.property] }}</span>
            </template>
          </el-table-column>
        </div>
        <!-- 编辑商品 显示的表头 -->
        <div v-if="enterType === 2">
          <el-table-column label="规格信息" align="center" fixed="left">
            <template slot-scope="scope">
              <span>
                {{ scope.row.levelPath }}
              </span>
            </template>
          </el-table-column>
        </div>
        <el-table-column
          label="库存（个/件）"
          :render-header="renderHeader"
          align="center"
          width="230"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              clearable
              v-model="scope.row.stock"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="现价（元）"
          :render-header="renderHeader"
          align="center"
          width="230"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              clearable
              v-model="scope.row.price"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="原价（元）"
          :render-header="renderHeader"
          align="center"
          width="230"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              clearable
              v-model="scope.row.priceOriginal"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="成本价（元）"
          :render-header="renderHeader"
          align="center"
          width="230"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              type="number"
              v-model="scope.row.priceCost"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  name: "GoodsSpecifications",
  props: {
    addgoodsinfo: {
      type: Object,
      required: true,
    },
    enterType: Number,
  },
  data() {
    return {
      alldisable: false, //编辑按钮进来 禁止编写规格 等信息
      showtable: false, //动态表格
      _showshowspecification: false, //规格新增板块 显示
      disabledinventory: false, //禁止 库存
      showspecification: false, //是否支持显示库存
      specificationstate: "下单减库存", //库存状态
      enablespecifications: false, //启用商品规格

      specificationForm: {
        stock: 0, //库存
        isShowStock: 0, //是否显示库存：0：否；1：是；默认为0
        inventoryReductionType: 1, //减库存的类型 1：下单减库存；2：付款减库存；3：永不减库存；默认为1；
        isUseSpecification: 0, //是否启用规格参数 0：否；1：是；默认为0
      },

      tableColumnList: {
        goodsSpecList: [],
        specItemAttrList: [],
      },
      privateGoodsItem: [
        {
          privateSpecName: null, //规格名
          dynamicTags: [], //规格值数组
          inputVisible: false,
          inputValue: null,
        },
      ],
    };
  },
  mounted() {
    if (this.enterType === 2) {
      this.tableColumnList.specItemAttrList =
        this.addgoodsinfo.specItemAttrList;

      if (
        this.addgoodsinfo.goodsSpecList &&
        this.addgoodsinfo.goodsSpecList.map
      ) {
        this.privateGoodsItem = this.addgoodsinfo.goodsSpecList.map((spec) => {
          return {
            privateSpecName: spec.specName,
            dynamicTags: spec.specItemList.map((item) => item.name),
            inputVisible: false,
            inputValue: null,
          };
        }); //回显 规格数据
      }
    }
  },
  created() {
    if (this.addgoodsinfo.goods.isUseSpecification === 1) {
      this.enablespecifications = true;
      this.showtable = true;
    }
    if (this.addgoodsinfo.goods.isShowStock === 1) {
      this.showspecification = true;
    }

    this.$emit("goodsspecifications", {
      specificationForm: this.specificationForm,
      tableColumnList: this.tableColumnList,
    });
  },
  methods: {
    emitspecification() {
      return this.tableColumnList;
    },
    Refresh() {
      if (
        this.addgoodsinfo.goodsSpecList.length == 0 ||
        this.addgoodsinfo.goodsSpecList.length < 2
      ) {
        this.$message({
          message: "规格项不能为空或小于两项！！",
          type: "warning",
        });
      } else {
        this.showtable = true;
      }
    },
    specificationstatehanle(e) {
      this.specificationstate = e;
      if (e === "下单减库存") {
        this.addgoodsinfo.goods.inventoryReductionType = 1;
      } else if (e === "付款减库存") {
        this.addgoodsinfo.goods.inventoryReductionType = 2;
      } else {
        this.addgoodsinfo.goods.inventoryReductionType = 3;
      }
    }, //减库存的类型 1：下单减库存；2：付款减库存；3：永不减库存；默认为1；
    // 添加规格
    addPrivateSpec(index) {
      this.privateGoodsItem.push({
        privateSpecName: "",
        dynamicTags: [],
        inputVisible: false,
        inputValue: "",
      });
    },
    delPrivateSpec(index) {
      this.privateGoodsItem.splice(index, 1);
    },
    handleInputConfirm(val, attr) {
      if (val) {
        attr.dynamicTags.push(val);
      }
      attr.inputVisible = false;
      attr.inputValue = "";
    },
    // 动态表格的某列的必填参数
    renderHeader(cerateElement, { column }) {
      return cerateElement("div", [
        cerateElement("span", column.label),
        cerateElement("span", {
          domProps: {
            innerHTML: "*",
          },
          style: {
            color: "red",
            fontSize: "16px",
            marginLeft: "5px",
          },
        }),
      ]);
    },
    handleClose(tag, item) {
      if (this.enterType !== 2) {
        item.dynamicTags.splice(item.dynamicTags.indexOf(tag), 1);
      }
    },
    showInput(attr, index) {
      attr.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs[`saveTagInput${index}`][0].$refs.input.focus();
      });
    },
    // 笛卡尔积算法
    cartesianProductOf(...args) {
      return args.reduce(
        (total, current) => {
          let ret = [];
          total.forEach((a) => {
            current.forEach((b) => {
              ret.push(a.concat([b]));
            });
          });
          return ret;
        },
        [[]]
      );
    },
    showspecificationhandle(e) {
      if (e) {
        this.addgoodsinfo.goods.isShowStock = 1;
      } else {
        this.addgoodsinfo.goods.isShowStock = 0;
      }
    }, //是否显示库存：0：否；1：是；默认为0
    enablespecificationshandle(e) {
      if (e) {
        this.addgoodsinfo.goods.isUseSpecification = 1;
      } else {
        this.addgoodsinfo.goods.isUseSpecification = 0;
      }
    }, //是否启用规格参数 0：否；1：是；默认为0
  },
  watch: {
    enablespecifications: function (newVal, oldVal) {
      if (newVal) {
        this.disabledinventory = true;
        this.$data._showshowspecification = true;
      } else {
        this.disabledinventory = false;
        this.$data._showshowspecification = false;
      }
    },
    // 监听规格数据
    calculateAttribute(newVal) {
      if (this.enterType === 1) {
        let cloneNewVal = JSON.parse(JSON.stringify(newVal));
        let attrName = []; //规格名数组
        let attrValue = []; //规格值数组
        for (let key in cloneNewVal) {
          attrName.push(key);
          attrValue.push(cloneNewVal[key]);
        }

        // 表格内容数据（笛卡尔积算法）
        let finalArr = this.cartesianProductOf(...attrValue);

        let tableObj = {
          specItemAttrList: [],
          goodsSpecList: [],
        };
        // 表格内容
        tableObj.specItemAttrList = finalArr.map((item) => {
          let obj = {
            id: null, //id
            goodsId: null, //商品id
            levelPath: Object.keys(item)
              .map((key) => item[key])
              .join(","), //规格属性path值
            code: null, //编码
            thumb: null, //缩略图
            sort: null, //排序
            stock: null,
          };
          for (let i = 0; i < item.length; i++) {
            obj[attrName[i]] = item[i];
          }
          return obj;
        });
        this.addgoodsinfo.specItemAttrList = tableObj.specItemAttrList; //表格内容数据

        let skuTableArr = Object.keys(newVal);
        tableObj.goodsSpecList = skuTableArr.map((item) => {
          return {
            id: null,
            goodsId: null,
            specName: item,
            specSort: null,
            specItemList: newVal[item].map((value) => {
              return {
                name: value,
                imgUrl: null,
                subId: null,
              };
            }),
          };
        });

        // this.addgoodsinfo.goodsSpecList = [...tableObj.goodsSpecList] // 表头
        this.addgoodsinfo.goodsSpecList = tableObj.goodsSpecList;
      } else if (this.enterType === 2) {
        console.log("现在是 watch中的this.enterType ===2 ");
      }
    },
    addgoodsinfo: {
      handler(newVal, oldVal) {
        // 当addgoodsinfo发生变化时执行的逻辑
      },
      deep: true, // 如果addgoodsinfo是一个对象，需要加上deep:true
    },
  },
  computed: {
    // 计算规格
    calculateAttribute() {
      // 初始化
      let obj = {};
      this.privateGoodsItem.forEach((item) => {
        // 判断有没有输入规格名
        if (item.privateSpecName) {
          //规格名:规格值     //'颜色':'尺寸'
          obj[item.privateSpecName] = item.dynamicTags;
        }
      });
      return obj;
    },
  },
};
</script>

<style lang="scss">
.goods-spec {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  // margin-top: 20px;
}
.goods-spec .goods-spec-add {
  margin-right: 15px;
}
.goods-container {
  width: 90%;
  margin-left: 5%;
  margin-top: 20px;
}
.goods-container .button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.goods-container .input-new-tag {
  width: 90px;
  margin-right: 10px;
  vertical-align: bottom;
}
.goods-container .el-tag {
  margin-right: 10px;
}
.goods-container .goods-content {
  margin-bottom: 10px;
  padding: 14px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fcfcfc;
}
.goods-content .goods-content-box {
  display: flex;
  align-items: center;
}
.goods-content-box .goods-content-left {
  flex: 1;
}
</style>
